"""
@Project ：zzzr_api_test 
@File    ：request_.py
@IDE     ：PyCharm 
@Author  ：ZSR
@Date    ：2023/2/23 23:05 
"""

import json
import requests
from tool import request_environment_info
from config.config import Environment
from tool.log import logger
from tool.allure_ import allure_description


class Requests:
    @classmethod
    def get(cls, url):
        url = request_environment_info(Environment)['ip'] + url
        headers = request_environment_info(Environment)['headers']
        logger.info(f'\nget请求的url:\n{url}')
        allure_description(f'\nget请求的url:\n{url}')
        response = requests.get(url=url, headers=headers)
        logger.info(f'\n{url}\t返回的结果:\n{response.json()}')
        return response.json()

    @classmethod
    def post(cls, url, data, headers):
        url = request_environment_info(Environment)['ip'] + url
        env_headers = request_environment_info(Environment)['headers']
        env_headers.update(headers)
        logger.info(f'\npost请求的url:\n{url}')
        allure_description(f'\npost请求的url:\n{url}')

        # 发送表单数据，使用data参数传递
        if 'application/x-www-form-urlencoded' in str(env_headers):
            response = requests.post(url=url, headers=env_headers, data=data)
            logger.info("最终的请求内容：" + "\n请求头：" + str(response.request.headers) + "\n请求体：" + str(response.request.body))
        # 如果接口支持application/json类型，则使用json参数传递
        elif 'application/json' in str(env_headers):
            response = requests.post(url=url, headers=env_headers, json=data)
        # 如果接口需要传递其他类型的数据比如 上传文件，调用下面的请求方法
        else:
            response = requests.post(url=url, data=data, headers=env_headers)
        logger.info(f'\n{url}\t返回的结果:\n{response.json()}')
        return response.json()


if __name__ == '__main__':
    # Requests.get('/banner/json')
    # print(Requests.get('/banner/json').json())
    # Requests.post('/post', {'data': 'data'})
    Requests.post('/lg/collect/25903/json', None, {'Content-Type': 'application/x-www-form-urlencoded'})
